package org.NooLab.openNLP;

import java.util.ArrayList;

import org.NooLab.itexx.comm.tcp.box.TcpBox;
import org.NooLab.openNLP.app.LinguistProperties;
import org.NooLab.openNLP.components.Actions;
import org.NooLab.structures.infra.remotely.ActionRequest;
import org.NooLab.utilities.files.DFutils;
import org.NooLab.utilities.logging.PrintLog;
import org.NooLab.utilities.strings.StringsUtil;



public class NlpFactory {

	TcpBox tcpBox;
	LinguistProperties lpProperties;

	NLPmain nlp;
	ArrayList<ActionRequest> requestedActions = new ArrayList<ActionRequest>();
	public Actions actions;
	
	PrintLog out = new PrintLog(2,false);
	StringsUtil strgutil = new StringsUtil();
	DFutils fileutil = new DFutils();
	
	
	// ========================================================================
	public NlpFactory(LinguistProperties lpProperties){
		this.lpProperties = lpProperties;
		
		actions = new Actions(this) ;
		nlp = new NLPmain(this) ;
	}
	// ========================================================================
	
	
	public static NlpFactory get(LinguistProperties lpProperties) {
		// 
		NlpFactory factory = new NlpFactory(lpProperties);
		return factory;
	}

	public void close() {
		// 
		nlp.close(1);
		tcpBox.getTcpReceiver().closePort() ;
		out.printErr(1, "NLP received a request to stop, now exiting (code:8)...");
		System.exit(8) ;
	}



	public TcpBox getTcpBox() {
		return tcpBox ; 
	}
	public void setTcpBox(TcpBox tcpBox) {
		// 
		this.tcpBox = tcpBox;
	}

	public void saveStartupTrace(String nlpFlavor, String traceInfo) {
		// 
		String userdir, cfgTraceFile;
		
		if (lpProperties.isITexxContext()){
			userdir = DFutils.createPath( lpProperties.getSystemRootDir(),"bin/");
		}else{ 
			userdir = fileutil.getUserDir(); // ???
		}
		
		cfgTraceFile = fileutil.createpath(userdir, "noonlp-.startup") ;
		
		
		fileutil.writeFileSimple(cfgTraceFile,traceInfo); 
		
	}

	public void go() {
		// 
		
		// setting TCP out, wrapped by observers through
		
		try {
			
			nlp.perform();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}



	public void handlingActionRequests(ActionRequest obj) {

		ActionRequest arq = (ActionRequest)obj;
		String cmd;
		
		cmd = arq.getCmdFamily().toLowerCase();
		if ((cmd==null) || (cmd.length()==0)){
			out.print(2, "received command was empty, thus nothing will be done.");
			return;
		}
		if (cmd.contentEquals("close")){
			actions.setClosingScheduled(true) ;
			
			if (arq.getCmdDetail().toLowerCase().contains("immediate")){
				close();
			}
		}
		requestedActions.add( arq ); 
	}


	public void checkForClosing(int sentResultsCount, int receivedStringsCount) {
		// 
		if (sentResultsCount == receivedStringsCount){
			// 
			close();
		}
	}
	
	
}
